<template>
  <view class="center-page">
    <view class="coupon-center-list">
      <template v-if="coupons && coupons.length > 0">
        <view class="center-coupon-card" v-for="(c, i) in coupons" :key="c.id || i">
          <view class="center-coupon-left">
            <view class="center-coupon-amount">
              <text class="center-yuan">¥</text>
              <text class="center-amount">{{ c.value }}</text>
            </view>
          </view>
          <view class="center-coupon-right">
            <view class="center-coupon-condition">{{ c.condition }}</view>
            <view class="center-coupon-limit">仅限{{ c.limit }}店铺使用</view>
            <view class="center-coupon-date">{{ c.valid }}</view>
            <view class="center-coupon-btn-wrap" @click="console.log('父元素点击')">
              <view 
                class="center-coupon-btn" 
                :class="{ disabled: c.status === 1 }" 
                @click="receiveCoupon(i)"
              >
                {{ c.status === 1 ? '已领取' : '领取' }}
              </view>
            </view>
          </view>
          <view class="center-coupon-notch top-notch"></view>
          <view class="center-coupon-notch bottom-notch"></view>
        </view>
      </template>
      <template v-else>
        <!-- 添加空状态显示 -->
        <view class="coupon-empty-box">
          <image class="coupon-empty-img" src="/static/car1.png" mode="widthFix"></image>
          <view class="coupon-empty-text">暂无优惠券</view>
        </view>
      </template>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import baseUrl from '@/untils/urlConfig';
import unirequest from '@/untils/unirequest';

// 获取当前登录用户ID
// const getCurrentUserId = () => {
//   const userInfo = uni.getStorageSync('userInfo');
//   if (!userInfo) {
//     uni.showToast({
//       title: '请先登录',
//       icon: 'none'
//     });
//     // 跳转到登录页面
//     setTimeout(() => {
//       uni.navigateTo({
//         url: '/pages/login/login'
//       });
//     }, 1500);
//     return null;
//   }
//   return userInfo.userId;
// };

// 响应式数据：优惠券列表
const coupons = ref([]); // 将静态数据清空

// 格式化日期函数
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  return `${year}.${month}.${day}`;
};

// 获取优惠券数据的方法
const fetchCoupons = async () => {
  // const userId = getCurrentUserId();
  // if (!userId) return; // 如果没有获取到用户ID，则不发送请求

  try {
    const response = await unirequest({
      url: baseUrl + '/chy/coupon/list', // 后端接口地址
      method: 'GET',
      // data: { // 传递userId，假设后端需要
      //   userId: userId
      //   // 如果需要分页或其他查询参数，可以在这里添加
      // },
    });

    // 检查响应状态码和业务状态码
    if (response.statusCode === 200 && response.data && response.data.code === 200) {
      // 假设后端返回的数据列表在 response.data.rows 中
      // 根据后端返回字段进行映射
      coupons.value = response.data.rows.map(item => ({
        id: item.id, // 保留id用于key
        value: item.discount, // 优惠金额
        condition: '满' + item.size + '元可用', // 使用门槛
        limit: item.name, // 优惠券名称/限制描述
        valid: `${formatDate(item.expirationStart)}—${formatDate(item.expirationEnd)}`, // 有效期
        status: item.status // 状态 (0:可领取 1:已领取，假设与后端一致)
        // 保留其他可能需要的字段
        // type: item.type,
        // discount: item.discount,
        // start: item.start,
        // isend: item.isend,
        // num: item.num,
        // size: item.size,
        // mid: item.mid
      })) || [];

      // uni.showToast({
      //   title: '获取优惠券数据成功',
      //   icon: 'success'
      // });
    } else {
      const errorMessage = response.data && response.data.msg ? response.data.msg : '获取优惠券数据失败';
      uni.showToast({
        title: errorMessage,
        icon: 'none'
      });
      console.error('获取优惠券数据失败:', response);
    }

  } catch (error) {
    console.error('请求失败:', error);
    uni.showToast({
      title: '网络请求失败',
      icon: 'none'
    });
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchCoupons();
});

// 领取优惠券方法 (目前只更新本地状态，如需调用后端接口，需另行实现)
const receiveCoupon = async (i) => {
  console.log('领取按钮点击，索引:', i); // 添加日志
  if (coupons.value[i].status === 0) {
    // TODO: 调用后端领取优惠券接口
    try {
    //   await uni.request({
    //     url: baseUrl + '/coupon/receive', // 假设领取接口
    //     method: 'POST',
    //     data: { couponId: coupons.value[i].id, userId: getCurrentUserId() },
    //     header: { 'Authorization': `Bearer ${uni.getStorageSync('token')}` }
    //   });
    //   coupons.value[i].status = 1;
    //   uni.showToast({ title: '领取成功', icon: 'success' });
    // } catch (error) {
    //   console.error('领取失败:', error);
    //   uni.showToast({ title: '领取失败', icon: 'none' });
    // }

    // 使用封装的 request 函数调用后端接口
    const response = await unirequest({
        url: baseUrl + '/chy/coupon/receive', // 假设后端接口是 /chy/coupon/receive
        method: 'POST',
        data: { couponId: coupons.value[i].id }, // 假设后端需要 couponId
        // request 函数会自动处理 token
    });

    if (response.statusCode === 200 && response.data && response.data.code === 200) {
        // 领取成功，更新本地状态
        coupons.value[i].status = 1; 
        uni.showToast({ title: '领取成功', icon: 'success' });
        // 如果后端返回了更新后的优惠券列表，可以考虑刷新列表或者只更新当前项
        // fetchCoupons(); // 如果需要刷新整个列表
    } else {
        // 处理后端返回的错误
        const errorMessage = response.data && response.data.msg ? response.data.msg : '领取失败';
        uni.showToast({ title: errorMessage, icon: 'none' });
        console.error('领取优惠券失败:', response);
    }

    } catch (error) {
      console.error('领取请求失败:', error);
      uni.showToast({ title: '网络请求失败', icon: 'none' });
    }

    // coupons.value[i].status = 1; // 暂时只更新本地状态 - 移除这行，状态更新移到成功回调中
  }
};

</script>

<style>
.center-page {
  background: #fafafa;
  min-height: 100vh;
  padding: 0;
}
.coupon-center-list {
  padding: 40rpx 0 0 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.center-coupon-card {
  width: 94vw;
  max-width: 720rpx;
  min-height: 220rpx;
  background: #fff;
  border-radius: 32rpx;
  margin-bottom: 36rpx;
  position: relative;
  display: flex;
  flex-direction: row;
  align-items: stretch;
  box-shadow: 0 8rpx 32rpx rgba(255, 140, 96, 0.10);
}
.center-coupon-left {
  width: 180rpx;
  background: linear-gradient(135deg, #ff8b5f 0%, #ff6a2f 100%);
  border-top-left-radius: 32rpx;
  border-bottom-left-radius: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}
.center-coupon-amount {
  display: flex;
  flex-direction: row;
  align-items: flex-end;
  justify-content: center;
}
.center-yuan {
  font-size: 40rpx;
  color: #fff;
  opacity: 0.95;
  margin-right: 4rpx;
  font-weight: 400;
  line-height: 1;
}
.center-amount {
  font-size: 64rpx;
  color: #fff;
  font-weight: bold;
  line-height: 1;
}
.center-coupon-right {
  flex: 1;
  background: #fff7f2;
  border-top-right-radius: 32rpx;
  border-bottom-right-radius: 32rpx;
  padding: 32rpx 32rpx 0 32rpx;
  display: flex;
  flex-direction: column;
  position: relative;
}
.center-coupon-condition {
  font-size: 32rpx;
  color: #ff6a2f;
  font-weight: bold;
  margin-bottom: 10rpx;
}
.center-coupon-limit {
  font-size: 24rpx;
  color: #222;
  margin-bottom: 18rpx;
}
.center-coupon-date {
  font-size: 22rpx;
  color: #b0b0b0;
  margin-bottom: 18rpx;
}
.center-coupon-btn-wrap {
  position: absolute;
  right: 32rpx;
  top: 32rpx;
}
.center-coupon-btn {
  background: linear-gradient(90deg, #ff8b5f 0%, #ff6a2f 100%);
  width: 45px;
  text-align: center;
  color: #fff;
  font-size: 28rpx;
  font-weight: 500;
  border-radius: 32rpx;
  padding: 8rpx 22rpx;
  box-shadow: 0 2rpx 8rpx rgba(255, 140, 96, 0.10);
  transition: background 0.2s;
}
.center-coupon-btn.disabled {
  background: #e0e0e0;
  color: #b0b0b0;
}
.center-coupon-notch {
  position: absolute;
  left: 180rpx;
  width: 32rpx;
  height: 32rpx;
  background: #fafafa;
  border-radius: 50%;
  z-index: 2;
}
.top-notch {
  top: -16rpx;
}
.bottom-notch {
  bottom: -16rpx;
}

/* 空状态样式 */
.coupon-empty-box {
  background: #fff;
  border-radius: 32rpx;
  margin: 40rpx 16rpx 0 16rpx;
  padding: 120rpx 0 120rpx 0;
  box-shadow: 0 8rpx 32rpx rgba(35,138,255,0.04);
  display: flex;
  flex-direction: column;
  align-items: center;
}
.coupon-empty-img {
  width: 220rpx;
  opacity: 0.25;
  margin-bottom: 32rpx;
}

.coupon-empty-text {
  color: #bbb;
  font-size: 30rpx;
  margin-top: 12rpx;
}
</style> 